<template>
  <div class="container">
    <el-card >
      <el-form ref="elForm" :model="formData" size="medium" label-width="100px">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="22"><el-alert title="说明：目前支持学科和关键字条件筛选" type="error" :closable="false" :style="{backgroundColor:'transparent',fontSize:'12px',color:'pink'}"> </el-alert></el-col>
          <el-col :span="2"
            >
              <el-button type="success" icon="el-icon-edit" @click="toAddNewQuestion">新增试题</el-button>
            </el-col
          >
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="学科" prop="subjectName">
                <el-select v-model="formData.subjectID" placeholder="请选择" clearable :style="{ width: '100%' }" @change="subjectChange()">
                  <el-option v-for="(item, index) in subjectNameOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="二级目录" prop="catalogID">
                <el-select v-model="formData.catalogID" placeholder="请选择" clearable :style="{ width: '100%' }" @change="catalogIDChange()">
                  <el-option v-for="(item, index) in catalogIDOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="标签" prop="tags">
                <el-select v-model="formData.tags" placeholder="请选择" clearable :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in tagsOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="关键字" prop="keyword">
                <el-input v-model="formData.keyword" placeholder="根据题干搜索" clearable :style="{ width: '100%' }"> </el-input>
              </el-form-item></div
          ></el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="试题类型" prop="questionType">
                <el-select v-model="formData.questionType" placeholder="请选择" clearable :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in questionTypeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="难度" prop="difficulty">
                <el-select v-model="formData.difficulty" placeholder="请选择" clearable :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in difficultyOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="方向" prop="direction">
                <el-select v-model="formData.direction" placeholder="请选择" clearable :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in directionOptions" :key="index" :label="item" :value="item" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="录入人" prop="creator">
                <el-select v-model="formData.creator" placeholder="请选择" clearable :style="{ width: '100%' }" @focus="getUsers()">
                  <el-option v-for="item in creatorOptions" :key="item.id" :label="item.username" :value="item.id" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="题目备注" prop="remarks">
                <el-input v-model="formData.remarks" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item label="企业简称" prop="shortName">
                <el-input v-model="formData.shortName" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="6">
            <el-form-item label="城市" prop="province">
              <el-row type="flex" :gutter="4">
                <el-col :span="12">
                  <el-select class="city" v-model="formData.province" placeholder="请选择" clearable :style="{ width: '100%' }" @change="provincesChange" @focus="getProvinces">
                    <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item" :value="item" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <el-select class="city" v-model="formData.city" placeholder="请选择" clearable :style="{ width: '100%' }">
                    <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="item" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-col> </el-row
            ></el-form-item>
          </el-col>
          <el-col :span="6"
            ><div class="grid-content bg-purple">
              <el-form-item size="large">
                <el-button type="primary" @click="resetForm">清除</el-button>
                <el-button @click="searchForm">搜索</el-button>
              </el-form-item>
            </div></el-col
          >
        </el-row>
      </el-form>
      <el-alert :title="`数据一共${total}条`" type="info" show-icon :closable="false" style="margin-bottom:15px"> </el-alert>

      <!-- 列表区域 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="number" label="试题编号"> </el-table-column>
        <el-table-column prop="subject" label="学科"> </el-table-column>
        <el-table-column prop="catalog" label="目录"> </el-table-column>
        <el-table-column prop="questionType" label="题型" :formatter="formQuestionType"> </el-table-column>
        <el-table-column prop="question" label="题干">
          <template v-slot="{ row }">
            <span>{{ row.question | formatHtml }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间">
          <template v-slot="{ row }">
            <span>{{ row.addDate | formatData }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" :formatter="formDifficulty"> </el-table-column>
        <el-table-column prop="creator" label="录入人" > </el-table-column>
        <!-- :formatter="formcreator" -->
        <el-table-column prop="operation" label="操作" width="200px">
          <template v-slot="{ row }">
            <el-button type="primary" icon="el-icon-view" size="mini" circle plain @click="previewCli(row)">
            </el-button>
            <el-button type="primary" icon="el-icon-edit" size="mini" circle plain @click="toAddNewQuestionById(row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" circle plain @click="delQuestions(row.id)"></el-button>
            <el-button type="success" icon="el-icon-check" size="mini" circle plain @click="toAddChoiceQuestion(row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="float: right "
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="curPage.pagesize"
        layout="prev, pager, next, sizes,jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 预览组件 -->
    <QuestionsPreview
    :showDialog.sync="showDialog"
    :previewData="previewData"
    :questionType="previewType"
    >

    </QuestionsPreview>
  </div>
</template>

<script>
import { simple as simpleSubjects } from '@/api/hmmm/subjects' // 导入简单学科列表
import { simple as simpleDirectorys } from '@/api/hmmm/directorys' // 导入简单二级目录列表
import { simple as simpleTags } from '@/api/hmmm/tags' // 导入简单标签列表
import { simple as simpleUsers } from '@/api/base/users' // 导入简单用户列表
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js' // 导入试题类型\难度\方向列表
import { provinces, citys } from '@/api/hmmm/citys' // 导入省会/城市列表
import { list as baseQuestionsList, remove as delQuestions, detail, choiceAdd } from '@/api/hmmm/questions.js' // 导入基础题库列表/删除/详情/加入精选
import { parseTime, html2Text } from '@/utils/index.js' // 导入时间/文本格式化方法
import QuestionsPreview from '@/module-hmmm/components/questions-preview.vue'// 导入预览组件
export default {
  components: {
    QuestionsPreview
  },
  props: [],
  data () {
    return {
      // form表单数据-双向绑定
      formData: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creator: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      },
      // 学科
      subjectNameOptions: [],
      // 二级目录
      catalogIDOptions: [],
      // 标签
      tagsOptions: [],
      // 试题类型
      questionTypeOptions: questionType,
      // 难度
      difficultyOptions: difficulty,
      // 方向
      directionOptions: direction,
      // 录入人
      creatorOptions: [],
      // 省份
      provinceOptions: [],
      // 城市
      cityOptions: [],
      // 表格数据
      tableData: [],
      // 表格数据总数
      total: 0,
      // 页码查询参数对象
      curPage: {
        page: 1, // 当前页码
        pagesize: 5 // 页容量:每页显示的行数
      },

      // 预览组件的显示与否
      showDialog: false,

      // 预览组件数据
      previewData: {

      },

      // 预览题目类型
      previewType: ''
    }
  },
  computed: {},
  watch: {},
  // 入口函数
  created () {
    this.getsubjectsList()
    this.getBaseQuestionsList()
  },
  mounted () {},
  methods: {
    // 表单搜索事件
    searchForm () {
      this.$refs.elForm.validate(async valid => {
        if (!valid) return
        const query = {}
        Object.keys(this.formData).filter(i => this.formData[i]).forEach(i => {
          query[i] = this.formData[i]
        }) // 判断是否有值
        console.log(query)
        const { data } = await baseQuestionsList(query)
        this.tableData = data.items
        this.total = data.counts
      })
    },

    // 表单清除事件
    resetForm () {
      this.$refs.elForm.resetFields()
      this.formData = {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creator: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      }
      this.getBaseQuestionsList()
    },

    // 获取学科数据列表事件
    async getsubjectsList () {
      const { data: subjectList } = await simpleSubjects()
      // console.log(subjectList)
      this.subjectNameOptions = subjectList
    },

    // 学科 下拉框 改变事件 / 获取二级目录数据列表事件
    async subjectChange () {
      // console.log(this.formData.subjectID)
      const { data: catalogIDList } = await simpleDirectorys({ subjectID: this.formData.subjectID })

      this.catalogIDOptions = catalogIDList
    },

    // 二级目录改变事件 / 获取标签数据列表事件
    async catalogIDChange () {
      const { data: tagslist } = await simpleTags({ subjectID: this.formData.subjectID })
      this.tagsOptions = tagslist
    },

    // 获取录入人数据列表事件
    async getUsers () {
      const { data: users } = await simpleUsers()
      // console.log(users)
      this.creatorOptions = users
    },

    // 获取省会数据列表事件
    getProvinces () {
      this.provinceOptions = provinces()
    },

    // 省会列表改变事件 / 获取各城市列表事件
    provincesChange () {
      this.cityOptions = citys(this.formData.province)
    },

    // 获取基础题库列表事件并渲染到页面
    async getBaseQuestionsList () {
      const { data } = await baseQuestionsList(this.curPage)
      this.tableData = data.items
      // console.log(this.tableData)
      this.total = data.counts
      if (this.curPage.page > data.pages) {
        this.handleCurrentChange(+data.pages)
      }
    },

    // 格式化题型/难度/录入人
    formQuestionType (row, column, cellValue, index) {
      return questionType.find(i => i.value === +cellValue).label
    },
    formDifficulty (row, column, cellValue, index) {
      return difficulty.find(i => i.value === +cellValue).label
    },

    // 切换页容量事件
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.curPage.pagesize = val
      this.getBaseQuestionsList()
    },

    // 切换页码事件
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.curPage.page = val
      this.getBaseQuestionsList()
    },

    // 跳转到试题录入新增页面事件
    toAddNewQuestion () {
      this.$router.push('new')
    },

    // 跳转到试题录入编辑页面事件
    toAddNewQuestionById (id) {
      this.$router.push(`new?id=${id}`)
    },

    // 跳转到试题录入添加页面事件
    toAddChoiceQuestion (id) {
      this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        choiceAdd({ id: id, choiceState: 1 })
        this.$message({
          type: 'success',
          message: '提示加入精选题库成功!'
        })
        this.getBaseQuestionsList()
        this.$router.push('choice')
      })
    },

    // 删除基础题库题目
    delQuestions (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delQuestions({ id })
        this.$nextTick(() => {
          this.getBaseQuestionsList()
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 预览按钮点击事件
    async previewCli (row) {
      const { data } = await detail(row)

      this.showDialog = true
      this.previewData = data
      console.log(this.previewData)
      this.previewType = data.questionType
    }

  },

  // 过滤器
  filters: {
    // html格式化事件
    formatHtml (val) {
      return html2Text(val)
    },

    // 时间格式化事件
    formatData (val) {
      return parseTime(val)
    }
  }
}
</script>

<style scoped lang="scss">
.el-card {
  margin: 10px;
  padding: 0 0 20px 0;
}
.el-row {
  // margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
  height: 60px;
}
.el-col {
  border-radius: 4px;
}
.el-pagination {
  padding-top: 20px;
}
</style>
